package com.aiju.common.http.interceptor;


import com.aiju.app.SimpleHttpCallback;
import com.aiju.support.aop.AInterceptor;
import com.aiju.support.aop.AInterceptorHandler;
import com.aiju.utils.L;
import com.aiju.utils.Util;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author: 佐为
 * @date: 2017-03-21 17:12
 * @version: V1.0
 * @Description: 日志打印
 */
public class HttpLogInterceptor extends AInterceptor {

    /**
     * 开始时间
     */
    private long beginTime;
    private SimpleHttpCallback callback;

    @Override
    protected void addMetodName() {
        methods.add("requestPost");
        methods.add("requestGet");
    }

    @Override
    protected Object interceptor(Object proxied, Method method, Object[] args) {
        return AInterceptorHandler.DEFAULT; //不做拦截
    }

    @Override
    public Object before(Object proxied, Method method, Object[] args) {
        beginTime = System.currentTimeMillis();
        if (!Util.isEmpty(args)) {

            //打印url
            L.d(TAG, "url:" + args[0].toString() + "\n");

            //打印参数
            if (args[1] != null) {
                Map<String, String> map = (Map) args[1];
                for (Map.Entry<String, String> entry : map.entrySet()) {
                L.d(TAG, "          "+entry.getKey() + " : " + entry.getValue());
                }
            }

            //请求回调
            if (args[2] != null && args[2] instanceof SimpleHttpCallback) {
                callback = (SimpleHttpCallback) args[2];
            }
        }
        return super.before(proxied, method, args);
    }

    @Override
    public Object after(Object proxied, Method method, Object[] args, Object methodReturn) {
        if (callback != null) {
            callback.addResult(new SimpleHttpCallback.IResult() {
                @Override
                public void result(String data) {
                    L.d(TAG, "result:" + data);
                    L.d(TAG, "          网络耗时 : " + (System.currentTimeMillis() - beginTime) / 1000f + " 秒 ");
                }
            });
        }
        return super.after(proxied, method, args, methodReturn);
    }
}
